#!/bin/bash
# SPDX-License-Identifier: MulanPSL-2.0+
# Copyright (c) 2020 Huawei Technologies Co., Ltd. All rights reserved.

iptables -I DOCKER-USER -d 169.254.169.254 -j DROP

[ "$deploy_k8s" = "true" ] && exit 0

[[ -f /etc/compass-ci/setup.yaml ]] && {
	br0_segment=$(awk '/^br0_segment:\s/ {print $2; exit}' /etc/compass-ci/setup.yaml)
}

: ${br0_segment:=172.18}

BR0_SUBNET=${br0_segment}.0.0/16

PUB_IFACE=$(ip route get 1.2.3.4 | awk '{print $5; exit}')
BR0_IFACE=br0

systemctl stop firewalld >/dev/null 2>&1

firewalld_status=$(systemctl is-active firewalld)

while [ $firewalld_status == active ]
do
	sleep 5
	firewalld_status=$(systemctl is-active firewalld)
done

systemctl start tuned >/dev/null 2>&1

# iptables -t nat -F
iptables -I FORWARD -s 172.17.0.0/16 -j ACCEPT
iptables -I INPUT -s 172.17.0.0/16 -j ACCEPT
iptables -w 10 -I FORWARD 1 -j ACCEPT
iptables -w 10 -A FORWARD -j ACCEPT
# iptables -w 10 -t nat -A POSTROUTING -o "$PUB_IFACE" -s $BR0_SUBNET -j MASQUERADE
iptables -w 10 -t nat -A POSTROUTING -j MASQUERADE
iptables -I INPUT -p udp --dport 67 -j ACCEPT
iptables -I INPUT -p udp --dport 69 -j ACCEPT

command -v firewall-cmd > /dev/null || {
	exit 0
}

[ "$(systemctl is-active firewalld)" == "active" ] || {
	exit 0
}

DOCKER0_SUBNET=172.17.0.0/16

firewall-cmd --zone=public --add-rich-rule="rule family=ipv4 source address=$DOCKER0_SUBNET accept"
firewall-cmd --zone=public --add-rich-rule="rule family=ipv4 source address=$BR0_SUBNET accept"
firewall-cmd --zone=public --add-rich-rule="rule family=ipv4 source address=0.0.0.0/32 accept"
firewall-cmd --zone=public --add-masquerade
